//
//  WDCardView.m
//  WDPolymerizeSDK
//
//  Created by little People on 2023/6/7.
//

#import "WDCardView.h"
#import "WDNariveAdView.h"
#import "WDSourceManager.h"
#import "WDNativeModel.h"
#import "WDBMSModel.h"
#import "WDNSLog.h"
#import "WDCardZDYManager.h"
#import "WDNativeManager.h"
#import "WDCallBackManager.h"
#import "WDAdStatusManager.h"

@interface WDCardView ()<GADVideoControllerDelegate,GADNativeAdDelegate>
@property (nonatomic, strong)WDNariveAdView *adContentView;
/// The native ad view that is being presented.
@property(nonatomic, strong) GADNativeAdView *nativeAdView;

@property (nonatomic, assign)BOOL isCustom;

@property (nonatomic, copy)NSString *deepLink;

@property (nonatomic, strong)NSTimer *cardTimer;

@property (nonatomic, copy)NSString *adType;
@end

@implementation WDCardView

- (instancetype)initWithFrame:(CGRect)frame isCustom:(BOOL)custom
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [[WDCallBackManager shareCallBackManager] adCallBackWithType:Show adSpace:[WDCallBackModel shareCallBackModel].adSpace message:@""];
        self.isCustom = custom;
        if (custom)
        {
            self.adType = @"自推广";
            [self customCardNativeAd];
        }
        else
        {
            self.adType = @"native";
            [self cardNativeAd];
        }
        WDLog(@"==:%@",[WDBMSModel shareBMSModel].cardConfig);
        if ([[WDBMSModel shareBMSModel].cardConfig[5] boolValue])
        {
            int interval = [[WDBMSModel shareBMSModel].cardConfig[6] intValue];
            self.cardTimer = [NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(refreshCardAd:) userInfo:nil repeats:YES];
        }
    }
    return self;
}

- (void)refreshCardAd:(NSTimer *)timer
{
    WDLog(@"refreshCardAd");
    if (!self.isCustom)
    {
        [[WDNativeManager shareNative] loadNativeAd];
        [WDNativeManager shareNative].adLoaderCallBackBlcok = ^{
            [self.adContentView removeFromSuperview];
            [self cardNativeAd];
        };
    }else{
        [self customCardNativeAd];
    }
}

- (void)customCardNativeAd
{
    CGFloat safeAreaTop = 0.0;
    CGFloat safeAreaBottom = 0.0;
    if (@available(iOS 11.0, *)) {
        UIViewController *rootViewController = [[[UIApplication sharedApplication].windows objectAtIndex:0] rootViewController];
        safeAreaTop = rootViewController.view.safeAreaInsets.top;
        safeAreaBottom = rootViewController.view.safeAreaInsets.bottom;
    }
    UIView *bv = [[UIView alloc] initWithFrame:self.bounds];
    bv.backgroundColor = [UIColor whiteColor];
//    bv.layer.cornerRadius = 8;
    [self addSubview:bv];
    
    WDCustomCardModel *model = [[WDCardZDYManager shareCardZDYManager] getCustomCardModel];
    self.deepLink = model.deepLink;
    WDLog(@"WDCustomCardModel====%@",model.appName);
    WDLog(@"WDCustomCardModel====%@",model.bannerUrl);
    
    if (!model)
    {
        [[WDAdStatusManager shareStatusManager] adShowFailedWithCode:0 message:@"no data" eventName:CARD_EVENT_NAME];
        [[WDCallBackManager shareCallBackManager] adCallBackWithType:ShowFail adSpace:[WDCallBackModel shareCallBackModel].adSpace message:@"no data"];
    }else{
        [[WDAdStatusManager shareStatusManager] cardAdShowWithEventName:CARD_EVENT_NAME adType:@"自推广"];
    }

    UIImageView *mediaImageView = [[UIImageView alloc] initWithFrame:CGRectMake(5, bv.frame.size.height/2-70, bv.frame.size.width-10, 140)];
    mediaImageView.image = model.bannerImage;
//    mediaImageView.center = bv.center;
    [bv addSubview:mediaImageView];
    

    
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, bv.frame.size.height-40, bv.frame.size.width-60, 40)];
    nameLabel.text = model.appName;
    [nameLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:20]];
    nameLabel.textAlignment = NSTextAlignmentCenter;
    nameLabel.textColor = [UIColor blackColor];
    nameLabel.adjustsFontSizeToFitWidth = YES;
    [bv addSubview:nameLabel];
    
    UIButton *callToButton = [[UIButton alloc] initWithFrame:CGRectMake(bv.frame.size.width-55, nameLabel.frame.origin.y, 50, 40)];
    [callToButton setBackgroundImage:[WDSourceManager WDImageWithName:@"zxf"] forState:UIControlStateNormal];
    [callToButton setTitle:@"安装" forState:UIControlStateNormal];
    [callToButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    callToButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [callToButton addTarget:self action:@selector(callToButton:) forControlEvents:UIControlEventTouchUpInside];
    [bv addSubview:callToButton];
    
    NSArray *cardConfig = [WDBMSModel shareBMSModel].cardConfig;
    NSString *isClose = [NSString stringWithFormat:@"%@",cardConfig[4]];
    
    UIButton *closeButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, bv.frame.size.width, bv.frame.size.height-40)];
    closeButton.hidden = ![isClose boolValue];
//    [closeButton setBackgroundColor:[UIColor redColor]];
    [closeButton addTarget:self action:@selector(closeAdView:) forControlEvents:UIControlEventTouchUpInside];
    [bv addSubview:closeButton];
    
    UIButton *closeButton1 = [[UIButton alloc] initWithFrame:CGRectMake(0, bv.frame.size.height-40, bv.frame.size.width-55, nameLabel.frame.size.height)];
    closeButton1.hidden = ![isClose boolValue];
//    [closeButton1 setBackgroundColor:[UIColor yellowColor]];
    [closeButton1 addTarget:self action:@selector(closeAdView:) forControlEvents:UIControlEventTouchUpInside];
    [bv addSubview:closeButton1];
}

- (void)callToButton:(UIButton *)sender
{
    if (self.deepLink.length > 0)
    {
        [[WDAdStatusManager shareStatusManager] cardAdClickWithEventName:CARD_EVENT_NAME adType:self.adType];
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.deepLink] options:@{} completionHandler:nil];
            
        }else{
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.deepLink]];
            
        }
        
        
    }
}

- (void)cardNativeAd
{
    self.backgroundColor = [UIColor clearColor];
    CGFloat safeAreaTop = 0.0;
    CGFloat safeAreaBottom = 0.0;
    if (@available(iOS 11.0, *)) {
        UIViewController *rootViewController = [[[UIApplication sharedApplication].windows objectAtIndex:0] rootViewController];
        safeAreaTop = rootViewController.view.safeAreaInsets.top;
        safeAreaBottom = rootViewController.view.safeAreaInsets.bottom;
    }

    
    self.adContentView = [[WDNariveAdView alloc] initWithFrame:self.bounds];
    self.adContentView.backgroundColor = [UIColor whiteColor];;
    [self addSubview:self.adContentView];
    
    WDNativeModel *model = [WDNativeModel shareNativeModel];
    
    if (!model)
    {
        [[WDAdStatusManager shareStatusManager] adShowFailedWithCode:0 message:@"no data" eventName:CARD_EVENT_NAME];
        [[WDCallBackManager shareCallBackManager] adCallBackWithType:ShowFail adSpace:[WDCallBackModel shareCallBackModel].adSpace message:@"no data"];
    }else{
        [[WDAdStatusManager shareStatusManager] cardAdShowWithEventName:CARD_EVENT_NAME adType:@"native"];
    }
    
    model.nativeAd.delegate = self;
    
    GADMediaView *mediaView = [[GADMediaView alloc] initWithFrame:CGRectMake(0, self.adContentView.frame.size.height/2-70, self.adContentView.frame.size.width, 140)];
    self.adContentView.mediaView = mediaView;
    [self.adContentView addSubview:self.adContentView.mediaView];
    
    UILabel *headline = [[UILabel alloc] initWithFrame:CGRectMake(0, self.adContentView.frame.size.height-40, self.adContentView.frame.size.width-60, 40)];
    headline.text = model.headline;
    [headline setFont:[UIFont fontWithName:@"Helvetica-Bold" size:20]];
    headline.textAlignment = NSTextAlignmentCenter;
    headline.textColor = [UIColor blackColor];
    headline.adjustsFontSizeToFitWidth = YES;
    self.adContentView.headlineView = headline;
    [self.adContentView addSubview:self.adContentView.headlineView];
    
    UIButton *callToButton = [[UIButton alloc] initWithFrame:CGRectMake(self.adContentView.frame.size.width-55, headline.frame.origin.y, 50, 40)];
    [callToButton setBackgroundImage:[WDSourceManager WDImageWithName:@"zxf"] forState:UIControlStateNormal];
    [callToButton setTitle:model.callToAction forState:UIControlStateNormal];
    [callToButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    callToButton.titleLabel.font = [UIFont systemFontOfSize:15];
    self.adContentView.callToActionView = callToButton;
    [self.adContentView addSubview:self.adContentView.callToActionView];
    
    
    NSArray *cardConfig = [WDBMSModel shareBMSModel].cardConfig;
    NSString *isClose = [NSString stringWithFormat:@"%@",cardConfig[4]];
    
    UIButton *closeButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, self.adContentView.frame.size.width, self.adContentView.frame.size.height-40)];
    closeButton.hidden = ![isClose boolValue];
//    [closeButton setBackgroundColor:[UIColor redColor]];
    [closeButton addTarget:self action:@selector(closeAdView:) forControlEvents:UIControlEventTouchUpInside];
    [self.adContentView addSubview:closeButton];
    
    UIButton *closeButton1 = [[UIButton alloc] initWithFrame:CGRectMake(0, self.adContentView.frame.size.height-40, self.adContentView.frame.size.width-55, headline.frame.size.height)];
    closeButton1.hidden = ![isClose boolValue];
//    [closeButton1 setBackgroundColor:[UIColor yellowColor]];
    [closeButton1 addTarget:self action:@selector(closeAdView:) forControlEvents:UIControlEventTouchUpInside];
    [self.adContentView addSubview:closeButton1];
    
    
    
    self.nativeAdView = self.adContentView;
    
//    self.nativeAdView.callToActionView.userInteractionEnabled = NO;

      // Associate the native ad view with the native ad object. This is
      // required to make the ad clickable.
    self.nativeAdView.nativeAd = model.nativeAd;
}

- (void)closeAdView:(UIButton *)sender
{
    [self hideAdView];
}

- (void)hideAdView
{
    [[WDCallBackManager shareCallBackManager] adCallBackWithType:Finish adSpace:[WDCallBackModel shareCallBackModel].adSpace message:@""];
    [self.cardTimer invalidate];
    self.cardTimer = nil;
    [WDNativeManager shareNative].adLoaderCallBackBlcok = nil;
    [WDNativeManager shareNative].isLoadNative = NO;
    [[WDNativeManager shareNative] loadNativeAd];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self removeFromSuperview];
    });
}

#pragma mark GADVideoControllerDelegate implementation
- (void)videoControllerDidEndVideoPlayback:(GADVideoController *)videoController {
  
    WDLog(@"videoControllerDidEndVideoPlayback");
}

#pragma mark GADUnifiedNativeAdDelegate
- (void)nativeAdDidRecordClick:(GADNativeAd *)nativeAd {
  WDLog(@"===========%s", __PRETTY_FUNCTION__);
}

- (void)nativeAdDidRecordImpression:(GADNativeAd *)nativeAd {
  WDLog(@"%s", __PRETTY_FUNCTION__);
}

- (void)nativeAdWillPresentScreen:(GADNativeAd *)nativeAd {
  WDLog(@"%s", __PRETTY_FUNCTION__);
}

- (void)nativeAdWillDismissScreen:(GADNativeAd *)nativeAd {
  WDLog(@"%s", __PRETTY_FUNCTION__);
}

- (void)nativeAdDidDismissScreen:(GADNativeAd *)nativeAd {
  WDLog(@"%s", __PRETTY_FUNCTION__);
}

- (void)nativeAdWillLeaveApplication:(GADNativeAd *)nativeAd {
  WDLog(@"%s", __PRETTY_FUNCTION__);
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
